<?php

/**
 * Louder Cache
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file docs/LICENSE.txt.
 *
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to info@loudertechnology.com so we can send you a copy immediately.
 *
 * @category Louder
 * @package NodeCommunicator
 * @subpackage Adapters
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */

/**
 * Realiza la comunicacion HTTP mediante la libreria PECL
 *
 * @category Louder
 * @package NodeCommunicator
 * @subpackage Adapters
 * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
 * @license New BSD License
 */
class PeclHTTPCommunicator implements CommunicatorInterface {

	/**
	 * Objeto HTTP
	 *
	 * @var HTTPRequest
	 */
	private $_http;

	/**
	 * Constructor de PeclHTTPCommunicator
	 *
	 * @param string $schema
	 * @param string $address
	 * @param string $uri
	 * @param string $method
	 * @param int $port
	 */
	public function __construct($scheme, $address, $uri, $method, $port = 80){
		if($port==80){
			$url = $scheme."://".$address."/$uri";
		} else {
			$url = $scheme."://".$address.":$port/$uri";
		}
		$fp = fopen("a.txt", "a");
		fputs($fp, $url."\n");
		fclose($fp);
		if($method=='POST'){
			$this->_http = new HttpRequest($url, HttpRequest::METH_POST);
			$this->_http->setPostFields($_POST);
		} else {
			$this->_http = new HttpRequest($url, HttpRequest::METH_GET);
		}
	}

	/**
	 * Establece los encabezados de la peticion
	 *
	 * @param array $headers
	 */
	public function setHeaders($headers){
		$this->_http->setHeaders($headers);
	}

	/**
	 * Agrega los parametros por GET a la peticion
	 *
	 * @access public
	 * @param array $queryParams
	 */
	public function prepareQueryData($queryParams){
		$this->_http->addQueryData($queryParams);
	}

	/**
	 * Envia la peticion HTTP
	 *
	 * @access public
	 */
	public function send(){
		try {
			$this->_http->send();
		}
		catch(HttpInvalidParamException $e){
			throw new NodeCommunicatorException($e->getMessage());
		}
	}

	/**
	 * Devuelve los headers recibidos de la peticion
	 *
	 * @return array
	 */
	public function getResponseHeaders(){
		return $this->_http->getResponseHeader();
	}

	/**
	 * Devuelve el cuerpo de la respuesta HTTP
	 *
	 * @return string
	 */
	public function getResponseBody(){
		return $this->_http->getResponseBody();
	}

	/**
	 * Devuelve el codigo de respuesta
	 *
	 * @return boolean
	 */
	public function getResponseCode(){
		return $this->_http->getResponseCode();
	}


}